package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.TbSkuDao;
import com.itheima.entity.TbSku;
import com.itheima.entity.TbSkuClass;
import com.itheima.entity.dto.TbPageDto;
import com.itheima.entity.dto.TbSkuDto;
import com.itheima.service.TbSkuClassService;
import com.itheima.service.TbSkuService;
import com.itheima.web.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Li
 * @description 针对表【tb_sku(商品表)】的数据库操作Service实现
 * @createDate 2022-08-25 20:11:21
 */
@Service
public class TbSkuServiceImpl extends ServiceImpl<TbSkuDao, TbSku> implements TbSkuService {
    @Autowired
    TbSkuDao tbSkuDao;
    @Autowired
    TbSkuClassService tbSkuClassService;


    @Override
    public Page<TbSkuDto> PageSku(Integer pageIndex, Integer pageSize) {
        Page<TbSku> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TbSku> wrapper = Wrappers.lambdaQuery(TbSku.class);
        Page<TbSku> skuPage = page(page, wrapper);
        TbPageDto<TbSkuDto> pageDto = new TbPageDto<>();
        TbPageDto<TbSkuDto> tbSkuTbPageDto = new TbPageDto<>();
        BeanUtils.copyProperties(skuPage, pageDto, "records");
        List<TbSku> skuPageRecords = skuPage.getRecords();
        List<TbSkuDto> tbSkuDtos = skuPageRecords.stream().map(tbSku -> {
            TbSkuDto tbSkuDto = new TbSkuDto();
            BeanUtils.copyProperties(tbSku, tbSkuDto);
            tbSkuDto.setDiscount(tbSku.getIsDiscount());
            TbSkuClass tbSkuClass = tbSkuClassService.findById(tbSkuDto.getClassId());
            tbSkuDto.setSkuClass(tbSkuClass);
            return tbSkuDto;
        }).collect(Collectors.toList());
        tbSkuTbPageDto.setCurrentPageRecords(tbSkuDtos);
        return tbSkuTbPageDto;
    }

    /**
     * 添加商品
     *
     * @param tbSku
     * @return
     */
    @Override
    public Boolean updateSave(TbSku tbSku) {
        if (StringUtils.isEmpty(tbSku.getSkuImage())) {
            throw new BusinessException("请填写规范商品名");
        }
        if (tbSkuDao.selectOne(Wrappers.lambdaQuery(TbSku.class)
                .eq(TbSku::getSkuName, tbSku.getSkuName())) != null) {
            throw new BusinessException("该商品已存在");
        }
        return save(tbSku);
    }
}

